<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    $file = $_FILES['file'];
    $uploadDir = 'assets/images/';
    $fileName = basename($file['name']);
    $uploadPath = $uploadDir . uniqid() . '_' . $fileName; // 使用 uniqid 避免文件名冲突

    // 检查文件类型
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
    if (!in_array($file['type'], $allowedTypes)) {
        echo json_encode(['url' => '', 'uploaded' => 0, 'error' => '不允许的文件类型']);
        exit;
    }

    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }
// 如果你用的是一级目录就把/blog/ 改成/
    if (move_uploaded_file($file['tmp_name'], $uploadPath)) {
        $url = 'http://' . $_SERVER['HTTP_HOST'] . '/blog/' . $uploadPath;
        echo json_encode(['url' => $url, 'uploaded' => 1, 'error' => null]);
    } else {
        echo json_encode(['url' => '', 'uploaded' => 0, 'error' => '上传失败']);
    }
}
?>
